package com.kinroy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinroy.reggie.common.BaseContxt;
import com.kinroy.reggie.entity.AddressBook;
import com.kinroy.reggie.entity.Orders;
import com.kinroy.reggie.entity.ShoppingCart;
import com.kinroy.reggie.mapper.OrdersMapper;
import com.kinroy.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrderDetailService ods;

    @Autowired
    private AddressBookService abs;

    @Autowired
    private ShoppingCartService ss;

    @Override
    @Transactional
    public void submit(Orders orders) {
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = abs.getById(addressBookId);
        //设置收货人名称
        orders.setConsignee(addressBook.getConsignee());
        //设置号码
        orders.setPhone(addressBook.getPhone());
        //设置地址
        orders.setAddress(addressBook.getDetail());
        //设置userid
        Long userId = BaseContxt.getid();
        orders.setUserId(userId);
        //设置订单总价
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = ss.list(lqw);
        BigDecimal countAll=new BigDecimal("0");

        for (int i = 0; i < list.size(); i++) {

            BigDecimal amount = list.get(i).getAmount();
            Integer number = list.get(i).getNumber();
            BigDecimal multiply = amount.multiply(new BigDecimal(number));
            countAll = countAll.add(multiply);

        }

        orders.setAmount(countAll);

        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //设置当前订单的状态
        orders.setStatus(2);

        //设置一下订单号
        String orderNumber = UUID.randomUUID().toString();
        orders.setNumber(orderNumber);

        this.save(orders);
        //订单完成后就可以清除用户的购物车了
        LambdaQueryWrapper<ShoppingCart> lqw1=new LambdaQueryWrapper<>();
        lqw1.eq(ShoppingCart::getUserId,userId);
        ss.remove(lqw1);

    }
}
